package com.gkzf.ai.module.crm.controller.admin.creditReport;

import com.gkzf.ai.module.crm.config.SseConfig;
import jakarta.annotation.security.PermitAll;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import reactor.core.publisher.Flux;

import java.io.IOException;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/creditReportSse")
public class CreditReportSseController {

    @Autowired
    private WebClient webClient;

    @Autowired
    private SseConfig sseConfig;


    // 接收前端请求，并返回 SSE 流
    @PostMapping(value = "/stream/{streamName}", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    @PermitAll
    public SseEmitter streamData(@RequestBody Map<String,String> map, @PathVariable String streamName){
        SseEmitter emitter = new SseEmitter(0L); // 设置超时时间
        String inputUrl = map.get("inputUrl");
        // 构建远程 SSE URL（携带参数）
        String remoteUrl = switch (streamName) {
            case "loan" -> sseConfig.getLoan();
            case "credit" -> sseConfig.getCredit();
            case "query" -> sseConfig.getQuery();
            case "basic" -> sseConfig.getBasic();
            default -> null;
        };
        if (remoteUrl == null) {
            return emitter;
        }
        remoteUrl = remoteUrl + "?input_url=" + inputUrl;

        // 使用 WebClient 请求远程 SSE 接口
        Flux<String> eventStream = webClient.post()
                .uri(remoteUrl)
                .retrieve()
                .bodyToFlux(String.class)
                .onBackpressureBuffer();
        try {
        // 订阅远程流，并推送给前端
        eventStream.subscribe(
                // 收到数据时的回调
                data -> {
                    try {
                        emitter.send(data); // 收到一条就发一条
                        log.info("转发数据: " + data);
                    } catch (IOException e) {
                        emitter.complete();
                    }
                },
                // 异常时的回调
                throwable -> {
                    try {
                        emitter.completeWithError(throwable);
                    } catch (Exception e) {
                        emitter.complete();
                    }
                },
                // 结束时的回调
                () -> {
                    try {
                        emitter.send("STREAM_END");
                    } catch (IOException e) {
                       log.info("最后一条转发数据IO异常: {}" ,e.getMessage());
                    }
                    emitter.complete(); // 远程流结束，向前端发送完成信号
                }
        );
    }catch (Exception e) {
        emitter.completeWithError(e);
    }
        return emitter;
    }
}
